package com.lsz.atm.db.dao_help;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.github.yuweiguocn.library.greendao.MigrationHelper;
import com.lsz.atm.db.CommodityBeanDao;
import com.lsz.atm.db.DaoMaster;
import com.lsz.atm.db.DaoSession;

import org.greenrobot.greendao.database.Database;

public class GreenDaoDbHelp extends DaoMaster.OpenHelper {

    private static final String DATABASE_NAME = "liang_atm_db";

    public GreenDaoDbHelp(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    public static DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            GreenDaoDbHelp daoDbHelp = new GreenDaoDbHelp(context, DATABASE_NAME, null);
            daoMaster = new DaoMaster(daoDbHelp.getWritableDatabase());
        }
        return daoMaster;
    }

    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
            @Override
            public void onCreateAllTables(Database db, boolean ifNotExists) {
                DaoMaster.createAllTables(db, ifNotExists);
            }

            @Override
            public void onDropAllTables(Database db, boolean ifExists) {
                DaoMaster.dropAllTables(db, ifExists);
            }
        }, CommodityBeanDao.class);
    }


}
